package com.huike.springboot1.demos.utils;

import javax.servlet.http.HttpSession;
import java.util.Random;

public class VerifyCodeUtil {
    // 生成6位数字验证码
    public static String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        char[] xxx = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};//去掉小写字母l，大写字母O
        for (int i = 0; i < 6; i++) {
            code.append(xxx[random.nextInt(60)]);
//            code.append(random.nextInt(10));//0-9的数字拼接
        }
        return code.toString();
    }

    // 存储验证码到Session（5分钟过期），用于存储一些用户信息，session存储于服务端，不用再本地进行修改
    public static void storeCode(HttpSession session, String email, String code) {
        session.setAttribute("VERIFY_CODE:" + email, code);
        session.setMaxInactiveInterval(60 * 5);
    }

    // 验证验证码，比对验证码是否相同
    public static boolean validateCode(HttpSession session, String email, String inputCode) {
        String storedCode = (String) session.getAttribute("VERIFY_CODE:" + email);
        return storedCode != null && storedCode.equals(inputCode);
    }
}
